﻿using UnityEngine;
using System.Collections;

public class Creep_AIv2 : MonoBehaviour {

	GameObject brevnoHide;
	GameObject molotokHide;
	GameObject Home;
	NavMeshAgent nav;
	Zamok_CPU cpu;
	Animator anim;
	public Transform targetPoint;
	bool working;
	bool hasBrevno;
	bool rabotaemb;
	bool iGorFinish;
	bool iGgorZakon4il;
	bool idu_domoy;
	bool zanyat;
	public float Idle_Time =10f;
	public float elapset_IdleT;
	//matrix is where


	GameObject build_tar;
	GameObject brevno;


	void Awake ()
	{
		Home = GameObject.Find("Home_01_01");
		brevnoHide = GameObject.Find ("/" + gameObject.name + "/Box008/Brevno");
		molotokHide = GameObject.Find ("/" + gameObject.name + "/CATRigHub001/CATRigSpine1/CATRigSpine2/CATRigSpine3/CATRigHub002/CATRigRArmCollarbone/CATRigRArm1/CATRigRArm2/CATRigRArmPalm/Molotok");
		nav = GetComponent<NavMeshAgent> ();
		cpu = GameObject.Find("Home_01_01").GetComponent<Zamok_CPU>();
		anim = GetComponent<Animator> ();


	}
	void Update()
	{
		anim.SetFloat("speed", nav.velocity.magnitude);

		if (elapset_IdleT < Idle_Time && zanyat == false)
		{elapset_IdleT += Time.deltaTime;}
		else if
		(elapset_IdleT>Idle_Time && zanyat == false && idu_domoy == false )
			
		{nav.SetDestination(Home.transform.position);
			idu_domoy = true;}
	}

	void OnTriggerEnter(Collider other)                                 
	{
		if (other.name == "Home" && idu_domoy)                       // Залезаем в дом 
		{
			idu_domoy = false;
			cpu.creepInBase++;
			Creepishe ya = cpu.arrCreeps.Find(p => p.creep.name == gameObject.name);
			cpu.arrCreeps.Remove(ya);
            Destroy(gameObject);
		}
	}





	public void build(GameObject zab, GameObject brevnishe) //получили задачу строить забор
	{
		build_tar = zab;
		brevno = brevnishe;
		if(!working){
			StartCoroutine (buildProcess());
			working = true;
			rabotaemb =false;
			iGorFinish=false;
			iGgorZakon4il=false;
			zanyat =true;
			elapset_IdleT =0f;
		}
	}


	IEnumerator  buildProcess ()
	{
        if (brevno == null)yield return null; 
        else
        {
            yield return StartCoroutine(go_to_brevno());  
            yield return StartCoroutine(travelEnd());
			yield return StartCoroutine(iGorTakeBrevno());
			while(!hasBrevno) {yield return null;}
			yield return StartCoroutine(iGorIdetkZeli());
			yield return StartCoroutine(travelEnd());
			transform.LookAt(build_tar.gameObject.transform);
			anim.SetTrigger("brevnodown");
			while(!rabotaemb){yield return null;}
			brevnoHide.GetComponent<MeshRenderer>().enabled = false;
			molotokHide.GetComponent<MeshRenderer> ().enabled = true;
			while(!iGgorZakon4il){yield return null;}
			anim.SetTrigger ("done_stroit");
			molotokHide.GetComponent<MeshRenderer> ().enabled = false;
			Creepishe miInlist = cpu.arrCreeps2.Find(p => p.creep.name == gameObject.name);
			miInlist.zada4a = "Stroim";
			miInlist.lastTask = "Stroim_zabor";
			zanyat = false;
			working = false;
        }
	}

	IEnumerator go_to_brevno()
	{
	    targetPoint = brevno.gameObject.GetComponentInChildren<TarPoint> ().point;
		nav.SetDestination (targetPoint.transform.position);
		yield return null;
	}

    IEnumerator travelEnd()
    {while(!pathComplete())
		{
			yield return null;
		}
    }
	IEnumerator iGorTakeBrevno()
	{
		transform.LookAt(brevno.transform);								// Пришли к бревну
		brevnoHide.GetComponent<MeshRenderer>().enabled = true;
		Destroy(brevno);
		anim.SetBool("hasbrevno", true);
		yield return null;

	}

	void IgorHaveBrevno(){hasBrevno = true;}

    void rabotaem(){rabotaemb = true; hasBrevno = false;}

	void zabanim()
	{build_tar.GetComponent<Animator> ().SetTrigger ("build");
	build_tar.GetComponent<zaborMaster> ().masterCreep = gameObject;}

	void buildingfinish(){iGorFinish=true;}

	public void donestroit(){iGgorZakon4il=true;}

	IEnumerator iGorIdetkZeli()
	{targetPoint = build_tar.gameObject.GetComponentInChildren<TarPoint>().point;
		nav.SetDestination(targetPoint.transform.position);
		anim.SetBool("hasbrevno", false);
		yield return null;}


	protected bool pathComplete()
	{if ( Vector3.Distance( nav.destination, nav.transform.position) <= nav.stoppingDistance)
		{if (!nav.hasPath || nav.velocity.sqrMagnitude == 0f)
			{return true;}}
		return false;}
	}
